﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace skvote
{
    public partial class GetCode : System.Web.UI.Page
    {
        private const string str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        protected void Page_Load(object sender, EventArgs e)
        {
            OutputImage(4);
        }
        private void OutputImage(int length)
        {
            string str = RndNumbers(length);
            Session["code"] = str;
            CreateImage(str);
        }
        private string RndNumbers(int length)
        {
            string nums = string.Empty;
            Random rand = new Random();
            for (int i = 0; i < length; i++)
            {
                nums += str.Substring(rand.Next(36),1);
            }
            return nums;
        }
        private System.Drawing.Color GetColor()
        {
            Random random_first = new Random((int)DateTime.Now.Ticks);
            System.Threading.Thread.Sleep(random_first.Next(50));
            Random random_second = new Random((int)DateTime.Now.Ticks);
            int red = random_first.Next(256);
            int green = random_second.Next(256);
            int blue = ((red+green)>400) ? 0 : (400-red-green);
            blue = blue > 255 ? 255 : blue;
            return System.Drawing.Color.FromArgb(red, green, blue);
        }
        private void CreateImage(string numbers)
        {
            int img_width = numbers.Length * 13+5;
            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(img_width, 20);
            System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(bitmap);
            graphic.Clear(System.Drawing.Color.White);
            Random rand = new Random();
            graphic.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.LightGray, 1), 0, 0, img_width-1, 19);
            System.Drawing.Font font = new System.Drawing.Font("Arial", 10);
            for (int i = 0; i < numbers.Length; i++)
            {
                string str_char = numbers.Substring(i, 1);
                System.Drawing.SolidBrush brush = new System.Drawing.SolidBrush(GetColor());
                System.Drawing.Point pos = new System.Drawing.Point(i * 13 + rand.Next(3) + 1, 1 + rand.Next(3));
                graphic.DrawString(str_char, font, brush, pos);

            }
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            Response.ClearContent();
            Response.ContentType = "image/jpg";
            Response.BinaryWrite(ms.ToArray());
            graphic.Dispose();
            bitmap.Dispose();
            Response.End();
        }

    }
}
